<template>
  <div class="container">
    <!-- 搜索和操作区域 -->
    <div class="operation-panel">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="科目名称">
          <el-input v-model="searchForm.name" placeholder="请输入科目名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加科目
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      v-loading="loading"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      style="width: 100%"
    >
      <el-table-column prop="name" label="科目名称" min-width="200" />
      <el-table-column prop="sort" label="排序" width="100" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="上级科目">
          <el-tree-select
            v-model="formData.parentId"
            :data="subjectTree"
            :props="treeProps"
            check-strictly
            placeholder="请选择上级科目"
            clearable
          />
        </el-form-item>
        <el-form-item label="科目名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入科目名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { SubjectService } from '@/api/questionBank'
const { getSubjectPage, addSubject, updateSubject, deleteSubject, getSubjectTree } = SubjectService
// 表格数据
const tableData = ref([])
const loading = ref(false)
const subjectTree = ref([])

// 树形选择器配置
const treeProps = {
  value: 'id',
  label: 'name',
  children: 'children'
}

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  parentId: 0,
  name: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入科目名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
}

// 初始化数据
onMounted(() => {
  fetchData()
  fetchSubjectTree()
})

// 获取科目树
const fetchSubjectTree = async () => {
  try {
    const res = await getSubjectTree()
    subjectTree.value = res.data
  } catch (error) {
    console.error('获取科目树失败:', error)
  }
}

// 获取表格数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const res = await getSubjectPage(params)
    tableData.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取科目列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  handleSearch()
}

// 添加科目
const handleAdd = () => {
  dialogTitle.value = '添加科目'
  resetForm()
  dialogVisible.value = true
}

// 编辑科目
const handleEdit = (row) => {
  dialogTitle.value = '编辑科目'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除科目
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该科目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteSubject(id)
    ElMessage.success('删除成功')
    fetchData()
    fetchSubjectTree() // 重新加载科目树
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: null,
    parentId: 0,
    name: '',
    sort: 0,
    status: 1
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (formData.id) {
      await updateSubject(formData)
      ElMessage.success('更新成功')
    } else {
      await addSubject(formData)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchData()
    fetchSubjectTree() // 重新加载科目树
  } catch (error) {
    console.error('操作失败:', error)
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  width: 100%;
  background: #fff;
  border-radius: 4px;
}

.operation-panel {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.action-buttons {
  margin-left: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
